/**
 * MIT License
 *
 * Copyright (c) 2024 小村程序员
 * Email: 397237738@qq.com
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package org.open.cobertura.core.output.tcp;

import org.open.cobertura.core.output.IOutputClient;
import org.open.cobertura.enums.CommonParams;

import java.io.*;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.logging.Logger;

/**
 * TCP输出运行时数据的客户端
 */
public class TCPOutputClient implements IOutputClient {
    private final static Logger logger = Logger.getLogger(TCPOutputClient.class.getName());
    public void dumpRuntimeData(String host,int port){
        try (Socket socket = new Socket(host,port); InputStream inputStream = socket.getInputStream()) {
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            out.println("dump");
            byte[] buffer = new byte[1024];
            byte[] totalBytes = new byte[0];
            int bytesRead = 0;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byte[] temp = new byte[totalBytes.length + bytesRead];
                System.arraycopy(totalBytes, 0, temp, 0, totalBytes.length);
                System.arraycopy(buffer, 0, temp, totalBytes.length, bytesRead);
                totalBytes = temp;
            }
            outputRuntimeData(totalBytes);
            logger.info("Data reception completed.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建探针数据文件
     * @param data
     */
    private synchronized void outputRuntimeData(byte[] data){
        try {
            String baseDir = System.getProperty("user.dir");
            String file=baseDir+"/"+ CommonParams.coberturaDataFile.getValue();
            File coberturaDataFile=new File(file);
            //没有文件就创建一个
            if(!coberturaDataFile.exists()) {
                coberturaDataFile.createNewFile();
            }
            Files.write(Paths.get(file), data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
